package org.qianji.goosql.field;

import java.util.List;
import java.util.Map;

import org.qianji.goosql.dql.QueryStatement;
import org.qianji.goosql.exception.FieldException;

/**
 * 子查询字段。
 * 
 * @author gmz
 * 
 */
public class SubQueryField extends AbstractField {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7659677417088215963L;

	private QueryStatement subQuery;

	/**
	 * 根据查询语句构造一个子查询字段。此处限定查询语句只需有一个查询字段，虽然该限定未必能保证最终查询正确。
	 * 
	 * @param subQuery
	 *            {@link QueryStatement QueryStatement} 子查询语句
	 */
	private SubQueryField(QueryStatement subQuery) {
		super();
		if (subQuery == null) {
			throw new NullPointerException("subQuery can't be null");
		}
		int fldSize = subQuery.getSelect().size();
		if (fldSize != 1) {
			throw new FieldException("the size of subQuery must be 1");
		}
		this.subQuery = subQuery;
	}

	/**
	 * 获取子查询语句。
	 * 
	 * @return {@link QueryStatement QueryStatement} 子查询语句
	 */
	public QueryStatement getSubQuery() {
		return subQuery;
	}

	@Override
	public String getField() {
		return toSql();
	}

	@Override
	public List<Object> getPlacedParameters() {
		return subQuery.getPlacedParameters();
	}

	@Override
	public Map<String, Object> getNamedParameters() {
		return subQuery.getNamedParameters();
	}

	@Override
	public String toSql() {
		StringBuffer fld = new StringBuffer("(").append(subQuery.toSql()).append(")");
		return fld.toString();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null || !(obj instanceof SubQueryField)) {
			return false;
		}
		if (subQuery.equals(((SubQueryField) obj).getSubQuery())) {
			return true;
		}
		return false;
	}

	@Override
	public int hashCode() {
		int hc = 37 * 17 + subQuery.hashCode();
		return hc;
	}

	@Override
	public String toString() {
		return toSql();
	}

}
